<template>
  <div style="position: relative; height: 100%">
    <!-- 表单设计器 -->
    <FcDesigner
      ref="designer"
      :height="designerHeight"
      :config="config"
      @repeat-field="handleRepeatField"
      @change="onFormDesignerChange"
    >
      <template #handle>
        <!--        <el-button round size="small" type="primary" @click="handleSave">-->
        <!--          <Icon class="mr-5px" icon="ep:plus" />-->
        <!--          保存-->
        <!--        </el-button>-->
        <div class="importHandle">
          <el-dropdown>
            <div class="el-dropdown-link">
              <button class="el-button el-button--primary el-button--small is-plain">
                <i class="fc-icon icon-preview">导入</i>
              </button>

              <!--            <span class="el-icon&#45;&#45;right">-->
              <!--&lt;!&ndash;              <arrow-down />&ndash;&gt;-->
              <!--            </span>-->
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="showPopup = true">导入JSON</el-dropdown-item>
                <!--                <el-dropdown-item @click="setImportOption">导入Options</el-dropdown-item>-->
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>
    </FcDesigner>

    <vxe-modal
      show-footer
      show-confirm-button
      show-cancel-button
      show-zoom
      v-model="showPopup"
      width="50%"
      :height="showPopupInnerHeight"
      :title="'导入JSON'"
      @confirm="confirmEvent"
      @cancel="cancelEvent"
      @zoom="setImportDialogZoom"
    >
      <div>
        <json-editor
          ref="jsonEditorRef"
          :height="showPopupJsonEditorHeight"
          :mode="'text'"
          :mainMenuBar="true"
          :statusBar="true"
          :darkTheme="true"
          :fullWidthButton="false"
          v-model="formDsgnVal"
        />
      </div>
    </vxe-modal>

    <!-- 表单保存的弹窗 -->
    <Dialog v-model="dialogVisible" title="保存表单" width="600">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
        <el-form-item label="表单名" prop="name">
          <el-input v-model="formData.name" placeholder="请输入表单名" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :label="dict.value"
            >
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </template>
    </Dialog>
  </div>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import * as FormApi from '@/api/bpm/form'
import FcDesigner from '@form-create/designer'
import { encodeConf, encodeFields } from '@/utils/formCreate'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { useFormCreateDesigner } from '@/components/FormCreate'
import { DsgnFormService } from '@/api/res/approval/DsgnFormService'
import { ref } from 'vue'
import { useApprovalDesignerStore } from '@/store/modules/dsgn/ApprovalDesigner'
import { VxeUI } from 'vxe-pc-ui'
import JsonEditor from 'vue3-ts-jsoneditor'
// import EfInputRule from "@/components/FormCreate/src/sn/EfInputRule";
import { useFormDesignerStore } from '@/store/modules/formDesigner/FormDesignerStore'

defineOptions({ name: 'FormCreateDesigner' })

// const designerHeight = ref(document.documentElement.clientHeight - 100) // 表单设计器高度
const designerHeight = ref(`calc(100vh - 120px)`) // 表单设计器高度
const { t } = useI18n() // 国际化
const message = useMessage() // 消息
const { push, currentRoute } = useRouter() // 路由
const { query } = useRoute() // 路由信息
const { delView } = useTagsViewStore() // 视图操作

const { setFormJson } = useFormDesignerStore()

const designer = ref() // 表单设计器
useFormCreateDesigner(designer) // 表单设计器增强
const dialogVisible = ref(false) // 弹窗是否展示
const formLoading = ref(false) // 表单的加载中：提交的按钮禁用
const formData = ref({
  name: '',
  status: CommonStatusEnum.ENABLE,
  remark: ''
})
const formRules = reactive({
  name: [{ required: true, message: '表单名不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 处理保存按钮 */
const handleSave = () => {
  dialogVisible.value = true
}

const showPopup = ref(false)
const showPopupInnerHeight = ref(500)
const showPopupJsonEditorHeight = ref(showPopupInnerHeight.value - 120)
const formDsgnVal = ref([])
const jsonEditorRef = ref()
const confirmEvent = () => {
  designer.value.setRule(formDsgnVal.value)
  // configJson.value={}
  formDsgnVal.value = []
}
const cancelEvent = () => {
  VxeUI.modal.message({
    content: '点击取消'
  })
}

const handleRepeatField = (rule, api) => {}
// 动态设置导入弹窗JSON编辑器的高度
const setImportDialogZoom = (res) => {
  showPopupJsonEditorHeight.value = res.$modal.getBox().offsetHeight - 120
}

const onFormDesignerChange = () => {
  const rules = designer.value.getRule()
  designerStore.setDsgnModelFormConfigJsonRule(rules)
  setFormJson(rules)
}

const config = ref({
  autoActive: true,
  fieldReadonly: false,
  showSaveBtn: false
})

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as FormApi.FormVO
    data.conf = encodeConf(designer) // 表单配置
    data.fields = encodeFields(designer) // 表单字段
    if (!data.id) {
      await FormApi.createForm(data)
      message.success(t('common.createSuccess'))
    } else {
      await FormApi.updateForm(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    close()
  } finally {
    formLoading.value = false
  }
}
/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push('/bpm/manager/form')
}

const designerStore = useApprovalDesignerStore()

if (!designerStore.designerModel.form || Object.keys(designerStore.designerModel).length === 0) {
  // 设置默认值
  designerStore.designerModel = {
    form: {
      configJson: '{}' // 假设默认值是一个空的 JSON 字符串
      // 其他默认属性...
    }
  }
}
const configJson = ref(designerStore.getDsgnModelFormConfigJson)

/** 初始化 **/
onBeforeUpdate(async () => {
  // // 场景一：新增表单
  // const id = query.id as unknown as number
  // if (!id) {
  //   return
  // }
  // // 场景二：修改表单
  // const data = await FormApi.getForm(id)
  // const data = await FormApi.getForm('1893925754010464257')

  // formData.value = data
  // setConfAndFields(designer, configJson.formConfig, data.formConfig)
  const config = designerStore.getDsgnModelFormConfigJson
  // designer.value?.addComponent(EfInputRule)
  if (config.formConfig) {
    designer.value.setOption(config.formConfig)
    designer.value.setRule(config.widgetList)
    setFormJson(config.widgetList)
  }
})

// 实现 DsgnFormService 接口
const dsgnFormService: DsgnFormService = {
  getFormData: () => {
    // const formData = designer.value.getOption()
    // return formData
  },
  getFormConfig: () => {
    const formConfig = designer.value.getOption()
    // const config = encodeConf(designer)
    // const fields = encodeFields(designer)
    const widgetList = designer.value.getRule()
    return {
      widgetList: widgetList,
      formConfig: formConfig
    }
  }
}

defineExpose({
  dsgnFormService
})
</script>

<style lang="scss">
@import '@/styles/FormCreate/customFormCreateDesigner';

.importHandle {
  display: flex;
  align-items: center;
  margin-right: 15px;
}
</style>
